package tech.jabari.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.jabari.constants.UMSConstant;
import tech.jabari.user.entity.User;
import tech.jabari.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static tech.jabari.constants.UMSConstant.USER_ID;
import static tech.jabari.constants.UMSConstant.WELCOME_URL_KEY;

/**
 * @author Jabari Lu
 * @title: UserLoginController
 * @description: 用户登录的控制器
 * @data 2020/8/27 14:20
 */
@Controller
public class UserLoginController  {

    @Autowired
    private UserService userService;


    @PostMapping("/userLogin.action")
    @ResponseBody
    protected Map<String,Object> doPost(String username,String pwd,
                                        HttpSession session) throws ServletException, IOException {
        List<User> queryList = userService.getUserByUsernameAndPwd(username, pwd);
        Map<String, Object> dataMap = new HashMap<>();
        if (null != queryList && queryList.size() > 0) {
            String key = UMSConstant.WELCOME_CAN_ACCESS; // accessWelcome表示可以访问：欢迎页面。
            session.setAttribute(WELCOME_URL_KEY,key);// 将可以访问的key，放入到session中。
            //将用户id放入到session中
            User user = queryList.get(0);
            session.setAttribute(USER_ID, user.getId());
            dataMap.put("msg", "ok");
        } else {
            dataMap.put("msg", "no");
        }
        return dataMap;
    }
}
